package com.talkweb.securitycamera.data.hadoopDB;

import com.talkweb.securitycamera.common.constans.FileType;
import com.talkweb.securitycamera.common.interfaces.dataprocess.FileCallback;
import com.talkweb.securitycamera.data.bean.FileNodeEntity;
import ohos.app.Context;
import ohos.data.distributed.common.ChangeNotification;
import ohos.data.distributed.common.FieldValueType;
import ohos.data.distributed.common.KvStoreObserver;
import ohos.data.distributed.common.SubscribeType;

import java.util.ArrayList;

/**
 * @version 1.0.1
 * @description:本地分布式数据库
 * @program: security-camera
 * @Author xiaozhijun
 * @Date 2021/1/29 9:08
 */
public class LocalHadoopDb extends BaseHadoopDb implements KvStoreObserver {

    private Context ctx;

    /**
     * 主界面刷新回调
     */
    private FileCallback fileCallback;

    public LocalHadoopDb(Context context, String storeId, FileCallback callback) {
        this.ctx = context;
        this.fileCallback = callback;
        initOrGetDB(context, storeId);
        if (getKvStore() != null) {
            getKvStore().subscribe(SubscribeType.SUBSCRIBE_TYPE_REMOTE, this);
        }
    }

    @Override
    public ArrayList<FileNodeEntity> getDbColumeInfo() {
        ArrayList<FileNodeEntity> entities = new ArrayList<>();
        entities.add(new FileNodeEntity("filePath", FieldValueType.STRING, false));
        entities.add(new FileNodeEntity("createDuration", FieldValueType.STRING));
        entities.add(new FileNodeEntity("fileName", FieldValueType.STRING));
        entities.add(new FileNodeEntity("type", FieldValueType.INTEGER));
        entities.add(new FileNodeEntity("crateTime", FieldValueType.LONG));
        return entities;
    }

    @Override
    protected String[] getDbIndexs() {
        return new String[]{"filePath"};
    }

    @Override
    public void onChange(ChangeNotification changeNotification) {
        //onChange方法实质上，在一个子线程里执行
        ctx.getUITaskDispatcher().asyncDispatch(() -> {
            //刷新
            if (fileCallback != null) {
                fileCallback.onDataChanged(FileType.FILE_TYPE_IMAGE);
            }
        });
    }
}
